<template>
  <div class="page-container home" v-if="userStore.userInfo.ageGroup === 0">
    <!-- 顶部区域 -->
    <div class="header">
      <div class="location">
        <span>{{userName}}</span>
      </div>
      <div class="search-bar" @click="onClickSearch">
        <van-icon name="search" />
        <span>搜医院</span>
      </div>
      <div class="mini-app">
        <van-icon name="exchange" @click="changeMode()"/>
      </div>
    </div>

    <!-- 轮播广告 -->
    <div class="banner">
      <van-swipe class="swipe" :autoplay="3000" indicator-color="white">
        <van-swipe-item v-for="(image, index) in bannerList" :key="index">
          <img :src="image.imageUrl" class="banner-img">
        </van-swipe-item>
      </van-swipe>
    </div>

    <!-- 主要服务 -->
    <div class="main-services">
      <div class="service-item" @click="goToService('就医陪诊')">
        <img src="../../assets/images/big_jiuyipeizhen.png" alt="就医陪诊">
      </div>
      <div class="service-item" @click="goToService('上门陪护')">
        <img src="../../assets/images/big_shangmenpeihu.png" alt="上门陪护">
      </div>
    </div>

    <!-- 快捷服务 -->
    <div class="quick-services">
      <div class="service-grid">
        <div class="grid-item" @click="goToService('上门陪护')">
          <img src="../../assets/images/home_shanmenpeihu.png" alt="上门陪护">
          <span>上门陪护</span>
        </div>
        <div class="grid-item" @click="goToService('代跑取药')">
          <img src="../../assets/images/home_daipaoquyao.png" alt="代跑取药">
          <span>代跑取药</span>
        </div>
        <div class="grid-item" @click="goToService('送取就医结果')">
          <img src="../../assets/images/home_songqujieguo.png" alt="送取就医结果">
          <span>送取结果</span>
        </div>
        <div class="grid-item" @click="goToService('诊前约号')">
          <img src="../../assets/images/home_zhenqianyuehao.png" alt="诊前约号">
          <span>诊前约号</span>
        </div>
        <div class="grid-item" @click="goToService('就医陪诊')">
          <img src="../../assets/images/home_jiuyipeizhen.png" alt="就医陪诊">
          <span>就医陪诊</span>
        </div>
      </div>
    </div>

    <!-- 推荐医院 -->
    <div class="hospital-section">
      <div class="hospital-list">
        <div class="hospital-item" v-for="(item, index) in hospitals" :key="index" @click="goToHospital(item)">
          <div class="hospital-card">
            <!-- <img src="../../assets/images/a9715ec00ff76629d662c61f0b0ae23a.png" :alt="item.name" class="hospital-image"> -->
            <img v-if="item.image" :src="item.image"  class="hospital-image">
            <img v-else src="../../assets/images/hospital.png"  class="hospital-image">
            <div class="hospital-info">
              <div class="hospital-name">{{ item.name }}</div>
              <div class="hospital-tags">
                <span class="tag level">{{ item.grade }}</span>
                <span class="tag type">{{ item.type }}</span>
              </div>
              <p class="hospital-address-old">{{ item.summary }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="page-container home" v-else>
    <!-- 顶部区域 -->
    <div class="header">
      <div class="location">
        <span>{{userName}}</span>
      </div>
      <div class="search-bar" @click="onClickSearch">
        <van-icon name="search" />
        <span>搜医院</span>
      </div>
      <div class="mini-app">
        <van-icon name="exchange" @click="changeMode()"/>
      </div>
    </div>

    <!-- 主要服务
    <div class="main-services-old">
      <div class="service-item-old" @click="goToService('就医陪诊')">
        <h2>就医陪诊</h2>
        <img src="../../assets/images/home_jiuyipeizhen_old.png" alt="就医陪诊">
      </div>
      <div class="service-item-old" @click="goToService('上门陪护')">
        <h2>上门陪护</h2>
        <img src="../../assets/images/home_shangmenpeihu_old.png" alt="上门陪护">
      </div>
      <div class="service-item-old" @click="goToService('诊前约号')">
        <h2>诊前约号</h2>
        <img src="../../assets/images/home_zhenqianyuehao_old.png" alt="诊前约号">
      </div>
      <div class="service-item-old" @click="goToService('代跑取药')">
        <h2>代跑取药</h2>
        <img src="../../assets/images/home_daipaoquyao_old.png" alt="代跑取药">
      </div>
      <div class="service-item-old" @click="goToService('送取就医结果')">
        <h2>送取就医结果</h2>
        <img src="../../assets/images/home_songqujiuyijieguo_old.png" alt="送取就医结果">
      </div>
    </div> -->
    <!-- 推荐医院 -->
    <div class="hospital-section">
      <div class="hospital-list">
        <div class="hospital-item" @click="goToService('就医陪诊')" style="margin-bottom: 25px;">
          <div class="hospital-card">
            <!-- <img src="../../assets/images/a9715ec00ff76629d662c61f0b0ae23a.png" :alt="item.name" class="hospital-image"> -->
            <img  src="../../assets/images/home_jiuyipeizhen.png"  class="hospital-image">
            <div class="hospital-info">
              <div class="hospital-name" style="font-size: 30px;margin-top: 15px,">就医陪诊</div>
              <p class="hospital-address">就医陪诊，值得托付</p>
            </div>
          </div>
        </div>
        <div class="hospital-item" @click="goToService('诊前约号')" style="margin-bottom: 25px;">
          <div class="hospital-card">
            <!-- <img src="../../assets/images/a9715ec00ff76629d662c61f0b0ae23a.png" :alt="item.name" class="hospital-image"> -->
            <img  src="../../assets/images/home_zhenqianyuehao.png"  class="hospital-image">
            <div class="hospital-info">
              <div class="hospital-name" style="font-size: 30px;margin-top: 15px">诊前约号</div>
              <p class="hospital-address">诊前约号，省心省力</p>
            </div>
          </div>
        </div>
        <div class="hospital-item" @click="goToService('上门陪护')" style="margin-bottom: 25px;"> 
          <div class="hospital-card">
            <!-- <img src="../../assets/images/a9715ec00ff76629d662c61f0b0ae23a.png" :alt="item.name" class="hospital-image"> -->
            <img  src="../../assets/images/home_shanmenpeihu.png"  class="hospital-image">
            <div class="hospital-info">
              <div class="hospital-name" style="font-size: 30px;margin-top: 15px">上门陪护</div>
              <p class="hospital-address">上门陪护，关怀备至</p>
            </div>
          </div>
        </div>
        <div class="hospital-item" @click="goToService('送取就医结果')" style="margin-bottom: 25px;">
          <div class="hospital-card">
            <!-- <img src="../../assets/images/a9715ec00ff76629d662c61f0b0ae23a.png" :alt="item.name" class="hospital-image"> -->
            <img  src="../../assets/images/home_songqujieguo.png"  class="hospital-image">
            <div class="hospital-info">
              <div class="hospital-name" style="font-size: 30px;margin-top: 15px">送取就医结果</div>
              <p class="hospital-address">送取结果，安全无忧</p>
            </div>
          </div>
        </div>
        <div class="hospital-item" @click="goToService('代跑取药')" style="margin-bottom: 25px;">
          <div class="hospital-card">
            <!-- <img src="../../assets/images/a9715ec00ff76629d662c61f0b0ae23a.png" :alt="item.name" class="hospital-image"> -->
            <img  src="../../assets/images/home_daipaoquyao.png"  class="hospital-image">
            <div class="hospital-info">
              <div class="hospital-name" style="font-size: 30px;margin-top: 15px">代跑取药</div>
              <p class="hospital-address">代跑取药，高效贴心</p>
            </div>
          </div>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { showDialog, showToast } from 'vant'
import { useRouter } from 'vue-router'
import banner1 from '../../assets/images/4ac4fb8ad87116f43d299e206a781c78.png'
import banner2 from '../../assets/images/6e8c0b88827f9d6d34efe292e3d21c80.png'
import { carouselApi, hospitalApi ,userApi} from '@/api'
import axios from 'axios'
import { useUserStore } from '@/stores/user'
const userStore = useUserStore()

const router = useRouter()

// 医院列表数据
const hospitals = ref([
  {
    id: 1,
    name: '武汉中心医院',
    image: '../../assets/images/a9715ec00ff76629d662c61f0b0ae23a.png',
    tags: ['三甲', '综合医院'],
    address: '武汉中心医院是一家位于中国湖北省武汉市的大型综合性医院。'
  },
  {
    id: 2,
    name: '协和医院',
    image: '../../assets/images/hospital2.png',
    tags: ['三甲', '综合医院'],
    address: '协和医院是中国的一家著名综合性医院，拥有一流的医疗设施和技术。'
  },
  {
    id: 3,
    name: '湘雅医院',
    image: '../../assets/images/hospital3.png',
    tags: ['三甲', '综合医院'],
    address: '湘雅医院是湘雅医院的附属医院，提供全面的医疗服务。'
  }
])

// 轮播图数据
const bannerList = ref([])

// 点击搜索
const onClickSearch = () => {
  router.push('/search')
}

// 跳转到医院详情
const goToHospital = (item) => {
  router.push({
    name: 'Hospital',
    query: {
      hospitalData: encodeURIComponent(JSON.stringify(item))
    }
  })
}

// 跳转到服务页面
const goToService = (type) => {
  let serviceCode = null
  switch(type) {
    case '就医陪诊':
    serviceCode = 1;
      break;
    case '诊前约号':
    serviceCode = 2;
      break;
    case '送取就医结果':
    serviceCode = 3;
      break;
    case '代跑取药':
    serviceCode = 4;
      break;
    case '上门陪护':
    serviceCode = 5;
      break;
    default:
    serviceCode = null;
      break;
  }
  router.push({
    path: '/service',
    query: { 
      type,
      serviceCode:serviceCode
     }
  })
}

const getCarouselListData = async () => {
  try {
    let params = {
      page: 1,
      size: 1000
    }
    const res = await carouselApi.getSlideList(params)
    
    if (res.code === 200) {
      // 获取token
      const token = localStorage.getItem('token')
      
      // 处理每个轮播图的URL
      const processedBanners = await Promise.all(
        res.data.records.map(async (banner) => {
          try {
            // 获取图片blob数据
            const response = await axios.get(banner.imageUrl, {
              headers: {
                'Authorization': `Bearer ${token}`
              },
              responseType: 'blob'
            })
            
            // 创建 Blob URL
            const blob = new Blob([response.data], { type: response.headers['content-type'] })
            return {
              ...banner,
              imageUrl: URL.createObjectURL(blob)
            }
          } catch (error) {
            console.error('处理轮播图失败：', error)
            return banner
          }
        })
      )
      
      bannerList.value = processedBanners
    }
  } catch (error) {
    console.error('获取轮播图数据失败：', error)
  }
}
const getHospitalListData = async () => {
  try {
    // let params = {
    //   page: 1,
    //   size: 1000
    // }
    const res = await hospitalApi.getHospitalList()
    if (res.code === 200) {
      // 获取token
      const token = localStorage.getItem('token')
      // 处理每个医院的图片URL
      const processedHospitals = await Promise.all(
        res.data.records.map(async (hospital) => {
          try {
            // 如果图片URL为空，直接返回原始数据
            if (!hospital.image) {
              return hospital
            }
            
            // 获取图片blob数据
            const response = await axios.get(hospital.image, {
              headers: {
                'Authorization': `Bearer ${token}`
              },
              responseType: 'blob'
            })
            
            // 创建 Blob URL
            const blob = new Blob([response.data], { type: response.headers['content-type'] })
            return {
              ...hospital,
              image: URL.createObjectURL(blob)
            }
          } catch (error) {
            console.error('处理医院图片失败：', error)
            return hospital
          }
        })
      )
      hospitals.value = processedHospitals
    }
  } catch (error) {
    console.error('获取医院列表数据失败：', error)
  }
}

const userName = ref('')


// 设置
const changeMode = () => {
  showDialog({
    title: '提示',
    message: `确定要切换${userStore.userInfo.ageGroup === 0 ? '老年人模式' : '青少年模式'}吗？`,
    theme: 'round-button',
    showCancelButton: true
  }).then(async () => {
    let userData =  userStore.userInfo
  userData.ageGroup = Number(!userData.ageGroup)
  userStore.setUserInfo(userData)
  let params = {
    ageGroup:userData.ageGroup
  }
  const res = await userApi.profile(params)
  if(res.code === 200){
    showToast('切换成功')
  }else {
    showToast('切换失败')
  }
  if(userData.ageGroup){
    console.log('目前是老年人模式')
  }else{
    console.log('目前是青少年模式')
  }
  })
}

onMounted( async () => {
  await getCarouselListData()
  await getHospitalListData()
  userName.value = JSON.parse(localStorage.getItem('userInfo')).nickname
  if (userName.value&&userName.value.length > 5) {
      // 截取前 5 个字符并添加..
      userName.value = userName.value.slice(0, 5) + '..';
    }

    let  havePayPassword = JSON.parse(localStorage.getItem('userInfo'))
  if(havePayPassword.hasPayPassword === 1){
    showToast('请先去 “我的” 页面设置支付密码，才能正常下单')
    return
  } 
})

// 在组件卸载时清理 Blob URLs
onUnmounted(() => {
  bannerList.value.forEach(banner => {
    if (banner.imageUrl && banner.imageUrl.startsWith('blob:')) {
      URL.revokeObjectURL(banner.imageUrl)
    }
  })
})
</script>

<style lang="scss" scoped>
.home {
  background: #f5f5f5;

  .header {
    display: flex;
    align-items: center;
    padding: 12px 16px;
    background: var(--primary-color);
    color: #fff;

    .location {
      display: flex;
      align-items: center;
      gap: 4px;
      font-size: 14px;
    }

    .search-bar {
      flex: 1;
      display: flex;
      align-items: center;
      gap: 8px;
      margin: 0 12px;
      padding: 6px 12px;
      background: rgba(255, 255, 255, 0.2);
      border-radius: 16px;
      font-size: 14px;

      .van-icon {
        font-size: 16px;
      }
    }

    .mini-app {
      font-size: 20px;
    }
  }

  .banner {
    width: 100%;
    padding: 12px 16px;
    height: auto;
    background: #f5f5f5;

    .swipe {
      height: 160px;
      border-radius: 8px;
      overflow: hidden;
      
      .banner-img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        display: block;
      }
    }
  }

  .main-services {
    margin: 12px;
    display: flex;
    gap: 8px;

    .service-item {
      flex: 1;
      height: 80px;
      border-radius: 8px;
      overflow: hidden;
      
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
  }

.main-services-old{
  margin: 12px;
  display: flex;
  flex-wrap: wrap;
  gap: 15px; /* 子元素之间的间距 */
  .service-item-old{
    flex: 0 0 calc(50% - 10px); /* 每个子元素宽度占父容器的 50%，减去间距 */
    height: 220px;
    box-sizing: border-box;
        img {
        width: 100%;
        height: 180px;
        object-fit: cover;
      }
  }
}
  
  .quick-services {
    margin: 12px;
    padding: 16px;
    background: #fff;
    border-radius: 8px;

    .service-grid {
      display: grid;
      grid-template-columns: repeat(5, 1fr);
      gap: 8px;

      .grid-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 4px;

        img {
          width: 44px;
          height: 44px;
          object-fit: contain;
        }

        span {
          font-size: 12px;
          color: #333;
          line-height: 1.2;
        }
      }
    }
  }

  .hospital-section {
    margin: 16px;
    margin-bottom: 80px;

    .hospital-list {
      .hospital-item {
        margin-bottom: 12px;
      }

      .hospital-card {
        display: flex;
        background: #fff;
        border-radius: 8px;
        padding: 12px;
        gap: 12px;

        .hospital-image {
          width: 80px;
          height: 80px;
          border-radius: 4px;
          object-fit: cover;
        }

        .hospital-info {
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: space-between;

          .hospital-name {
            font-size: 16px;
            font-weight: 500;
            color: #333;
            margin-bottom: 8px;
          }

          .hospital-tags {
            display: flex;
            gap: 8px;
            margin-bottom: 8px;

            .tag {
              padding: 2px 8px;
              font-size: 12px;
              border-radius: 4px;
              
              &.level {
                color: #07c160;
                background: rgba(7, 193, 96, 0.1);
              }
              
              &.type {
                color: #3b82f6;
                background: rgba(59, 130, 246, 0.1);
              }
            }
          }

          .hospital-address {
            margin: 0;
            font-size: 12px;
            color: #999;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
          }
          .hospital-address-old {
            margin: 0;
            font-size: 12px;
            color: #999;

          }
        }
      }
    }
  }
}
</style> 